package com.lht.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lht.admin.constants.DataValidConstant;
import com.lht.admin.dao.TargetDao;
import com.lht.admin.entity.OrderStatisticsEntity;
import com.lht.admin.entity.SysUserEntity;
import com.lht.admin.entity.TargetEntity;
import com.lht.admin.service.OrderStatisticsService;
import com.lht.admin.service.SysUserService;
import com.lht.admin.service.TargetService;
import com.lht.admin.utils.ListUtil;
import com.lht.admin.utils.QueryPlus;
import com.lht.admin.utils.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 目标管理表Service实现类
 *
 * @author ZhengZhanWu
 * @date 2020-01-14 23:42:37
 */
@Service("targetService")
public class TargetServiceImpl extends ServiceImpl<TargetDao, TargetEntity> implements TargetService {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private OrderStatisticsService orderStatisticsService;

    @Override
    public List<TargetEntity> queryAll(Map<String, Object> params) {
        return baseMapper.queryAll(params);
    }

    @Override
    public Page queryPage(Map<String, Object> params) {
        //排序
        params.put("sidx", "T.id");
        params.put("asc", false);
        Page<TargetEntity> page = new QueryPlus<TargetEntity>(params).getPage();

        List<TargetEntity> list = baseMapper.selectTargetPage(page, params);

        if (ListUtil.isNotEmpty(list)) {
            loadAgentInfo(list);
            loadStaticsInfo(list);
            calculateProcess(list);
        }

        return page.setRecords(list);
    }

    /**
     * 计算进度
     *
     * @param list list
     */
    private void calculateProcess(List<TargetEntity> list) {
        for (TargetEntity t : list) {
            OrderStatisticsEntity statisticsInfo = t.getOrderStatisticsInfo();
            if (statisticsInfo != null) {
                BigDecimal planOrder = new BigDecimal(t.getPlanTotalOrder());
                BigDecimal planAmount = t.getPlanTotalOrderAmount();

                BigDecimal totalOrder = new BigDecimal(statisticsInfo.getTotalOrder());
                BigDecimal totalOrderAmount = statisticsInfo.getTotalOrderAmount();

                t.setProcessOfOrder(totalOrder.divide(planOrder, 2));
                t.setProcessOfMoney(totalOrderAmount.divide(planAmount, 2));

            } else {
                t.setProcessOfOrder(BigDecimal.ZERO);
                t.setProcessOfMoney(BigDecimal.ZERO);
            }
        }
    }

    /**
     * 加载业务员信息
     *
     * @param list 目标列表
     */
    private void loadAgentInfo(List<TargetEntity> list) {
        for (TargetEntity t : list) {
            SysUserEntity agent = sysUserService.queryObject(t.getPromoUserId());
            t.setAgentInfo(agent);
        }
    }


    /**
     * 加载统计数据
     *
     * @param list list
     */
    private void loadStaticsInfo(List<TargetEntity> list) {
        List<Long> promoUserIdList = list.stream().map(TargetEntity::getPromoUserId).collect(Collectors.toList());
        List<OrderStatisticsEntity> staticsInfos = orderStatisticsService.getByAgents(promoUserIdList);

        for (TargetEntity t : list) {
            OrderStatisticsEntity match = null;
            for (OrderStatisticsEntity sts : staticsInfos) {
                if (isMatchUp(t, sts)) {
                    match = sts;
                    break;
                }
            }
            if (null != match) {
                t.setOrderStatisticsInfo(match);
            }
        }
    }


    private boolean isMatchUp(TargetEntity origin, OrderStatisticsEntity compare) {
        if (null == origin || compare == null) {
            return false;
        }

        Long originId = origin.getPromoUserId();
        Long compareId = compare.getPromoUserId();

        if (null != compareId && !compareId.equals(originId)) {
            return false;
        }

        String originMonth = origin.getMonth();
        String compareMonth = compare.getMonth();

        return StringUtils.isNotEmpty(originMonth) && originMonth.equals(compareMonth);
    }

    @Override
    public boolean add(SysUserEntity operator, TargetEntity target) {

        Date date = new Date();

        target.setCreateAt(date);
        target.setUpdateAt(date);

        target.setUpdateUserId(operator.getUserId());
        target.setCreateUserId(operator.getUserId());

        return this.save(target);
    }

    @Override
    public boolean update(TargetEntity target) {
        return this.updateById(target);
    }

    @Override
    public boolean delete(SysUserEntity sysUserEntity, Long id) {
        Long[] arr = {id};
        return deleteBatch(sysUserEntity, arr);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteBatch(SysUserEntity sysUserEntity, Long[] ids) {
        // 构建更新条件
        UpdateWrapper<TargetEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in(TargetEntity.ID, Arrays.asList(ids));
        updateWrapper.set(TargetEntity.IS_DELETE, DataValidConstant.IS_DELETE_TRUE_STR);
        updateWrapper.set(TargetEntity.UPDATE_AT, new Date());

        return update(updateWrapper);
    }
}
